import numpy

BLACK_FLAG = 0


# 返回一个二维list
# list[i] 表示一条路径
# list[i][j] 表示一个坐标 是（x, y）的二元组
# 输入的image_arr是一个numpy二维01矩阵 0 表示黑像素 1表示白像素
def get_paths(image_arr):
    paths = []
    while path := get_one_path(image_arr):
        paths.append(path)
    return paths


def get_one_path(image_arr):
    # 左上角第一个黑点
    x, y = find_first_black(image_arr)
    if x == -1:
        return None
    path = [(x, y)]
    image_arr[x, y] = 1
    next_x, next_y = check_next(image_arr, x, y)
    while next_x != -1:
        path.append((next_x, next_y))
        x, y = next_x, next_y
        image_arr[x, y] = 1
        next_x, next_y = check_next(image_arr, x, y)
    return path


def check_next(image_arr, x, y, level=3):
    # 像素半径顺时针画圆
    # 一个像素范围的
    next_1 = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]
    # 两个像素范围的
    next_2 = [(2, 0), (2, 1), (2, 2), (1, 2), (0, 2), (-1, 2), (-2, 2), (-2, 1),
              (-2, 0), (-2, -1), (-2, -2), (-1, -2), (0, -2), (1, -2), (2, -2), (2, -1)]
    # 三个像素范围的
    next_3 = [(3, 0), (3, 1), (3, 2), (3, 3), (2, 3), (1, 3), (0, 3), (-1, 3),
              (-2, 3), (-3, 3), (-3, 2), (-3, 1), (-3, 0), (-3, -1), (-3, -2), (-3, -3),
              (-2, -3), (-1, -3), (0, -3), (1, -3), (2, -3), (3, -3), (3, -2), (3, -1)]
    next_x, next_y = _check_next(image_arr, next_1, x, y)
    if level >= 2 and next_x == -1:
        next_x, next_y = _check_next(image_arr, next_2, x, y)
    if level >= 3 and next_x == -1:
        next_x, next_y = _check_next(image_arr, next_3, x, y)
    return next_x, next_y


def _check_next(image_arr, next_n, x, y):
    for dx, dy in next_n:
        next_x = x + dx
        next_y = y + dy
        if 0 < next_x < len(image_arr) and 0 < next_y < len(image_arr[0]) \
                and image_arr[next_x, next_y] == BLACK_FLAG:
            return next_x, next_y
    return -1, -1


def find_first_black(image_arr):
    # 获取第一个黑点
    for i in range(1, len(image_arr)):
        for j in range(1, len(image_arr[i])):
            if image_arr[i][j] == BLACK_FLAG:
                return i, j
    return -1, -1


if __name__ == '__main__':
    image_array = numpy.load('huan.npy')

    # cv2.imshow('view', image_array)
    # cv2.waitKey(0)
    print(len(image_array), len(image_array[0]))

    paths = get_paths(image_array)

    # turtle 画图
    import turtle

    turtle.screensize(len(image_array[0]), len(image_array))
    turtle.reset()
    turtle.setworldcoordinates(0, len(image_array), len(image_array[0]), 0)
    turtle.pensize(5)
    turtle.speed(2)
    turtle.pencolor("black")

    for i in range(len(paths)):
        turtle.penup()
        x, y = paths[i][0]
        turtle.goto(y, x)
        turtle.pendown()
        for x, y in paths[i]:
            turtle.goto(y, x)
        turtle.penup()

    turtle.done()
    # from time import sleep
    #
    # sleep(100)
